"""
高级使用示例
"""
import asyncio
from typing import List, Dict, Any
from k8s_deployment_extractor import K8sResourceAnalyzer

class AdvancedAnalyzer:
    """高级分析器类"""
    
    def __init__(self, config_path: str = None):
        self.analyzer = K8sResourceAnalyzer(config_path)
        self.resources: List[Dict[str, Any]] = []
    
    async def load_resources_from_file(self, file_path: str) -> None:
        """
        从文件异步加载资源
        
        Args:
            file_path: 资源文件路径
        """
        # 模拟异步加载
        await asyncio.sleep(0.1)
        # TODO: 实现实际的文件加载逻辑
        pass
    
    async def load_resources_from_directory(self, dir_path: str) -> None:
        """
        从目录异步加载资源
        
        Args:
            dir_path: 资源目录路径
        """
        # 模拟异步加载
        await asyncio.sleep(0.1)
        # TODO: 实现实际的目录加载逻辑
        pass
    
    async def analyze_resources(self) -> Dict[str, Any]:
        """
        异步分析资源
        
        Returns:
            分析结果
        """
        # 添加资源
        self.analyzer.add_resources(self.resources)
        
        # 并行执行健康检查和依赖分析
        health_task = asyncio.create_task(self._check_health())
        dependency_task = asyncio.create_task(self._analyze_dependencies())
        
        # 等待所有任务完成
        health_result, dependency_result = await asyncio.gather(
            health_task, dependency_task
        )
        
        return {
            'health': health_result,
            'dependencies': dependency_result
        }
    
    async def _check_health(self) -> Dict[str, Any]:
        """异步执行健康检查"""
        return self.analyzer.check_health()
    
    async def _analyze_dependencies(self) -> Dict[str, Any]:
        """异步执行依赖分析"""
        return self.analyzer.analyze_dependencies()
    
    def export_reports(self, output_dir: str) -> None:
        """
        导出所有报告
        
        Args:
            output_dir: 输出目录
        """
        # 导出健康报告（多种格式）
        self.analyzer.export_health_report(
            f"{output_dir}/health_report.yaml", "yaml"
        )
        self.analyzer.export_health_report(
            f"{output_dir}/health_report.json", "json"
        )
        self.analyzer.export_health_report(
            f"{output_dir}/health_report.html", "html"
        )
        
        # 导出依赖报告（多种格式）
        self.analyzer.export_dependency_report(
            f"{output_dir}/dependency_report.yaml", "yaml"
        )
        self.analyzer.export_dependency_report(
            f"{output_dir}/dependency_report.json", "json"
        )
        self.analyzer.export_dependency_report(
            f"{output_dir}/dependency_report.html", "html"
        )
    
    def get_resource_graph(self) -> Dict[str, Any]:
        """
        获取资源关系图
        
        Returns:
            资源关系图数据
        """
        return {
            'nodes': self._get_resource_nodes(),
            'edges': self._get_resource_edges()
        }
    
    def _get_resource_nodes(self) -> List[Dict[str, Any]]:
        """获取资源节点数据"""
        nodes = []
        for resource in self.resources:
            nodes.append({
                'id': f"{resource['metadata']['namespace']}/{resource['metadata']['name']}",
                'type': resource['kind'],
                'status': self.analyzer.get_resource_details(
                    f"{resource['metadata']['namespace']}/{resource['metadata']['name']}"
                )['status']
            })
        return nodes
    
    def _get_resource_edges(self) -> List[Dict[str, Any]]:
        """获取资源边数据"""
        edges = []
        for resource in self.resources:
            resource_id = f"{resource['metadata']['namespace']}/{resource['metadata']['name']}"
            dependencies = self.analyzer.get_resource_dependencies(resource_id)
            for dep in dependencies:
                edges.append({
                    'source': resource_id,
                    'target': dep,
                    'type': 'depends_on'
                })
        return edges

async def main():
    # 创建高级分析器
    analyzer = AdvancedAnalyzer()
    
    # 加载资源
    await analyzer.load_resources_from_file("resources/deployment.yaml")
    await analyzer.load_resources_from_directory("resources")
    
    # 分析资源
    results = await analyzer.analyze_resources()
    print("分析结果:", results)
    
    # 导出报告
    analyzer.export_reports("reports")
    
    # 获取资源关系图
    graph = analyzer.get_resource_graph()
    print("资源关系图:", graph)

if __name__ == "__main__":
    asyncio.run(main()) 